package com.rainbow.utils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;

/*
 * @author kingboy
 * @Date 2017/7/22 下午2:12
 * @Description LocalDateTimeUtils is used to Java8中的时间类
 */
public class LocalDateTimeUtils {

    public static final String DEFAULT_DATETIME_FORMAT      = "yyyy-MM-dd HH:mm:ss";

    public static final String DEFAULT_DATE_FORMAT          = "yyyy-MM-dd";

    public static final String DEFAULT_DATEFULLDATE_FORMAT  = "yyyyMMdd";

    public static final String DEFAULT_YEAR_FORMAT          = "yyyy";

    public static final String DEFAULT_MONTH_FORMAT         = "MM";

    public static final String DEFAULT_HM_FORMAT            = "HH:mm";

    public static final long MILLISECONDS_A_DAY             = 24 * 3600 * 1000;

    public static final long MILLISECONDS_A_HOUR            = 3600 * 1000;

    public static final long MILLISECONDS_A_SECOND          = 1000;

    public static final long MILLISECONDS_A_MIN             = MILLISECONDS_A_SECOND * 60;

    public static final String DEFAULT_DATEFULLTIME_FORMAT  = "yyyyMMddHHmmss";

    //获取当前时间的LocalDateTime对象
    //LocalDateTime.now();

    //根据年月日构建LocalDateTime
    //LocalDateTime.of();

    //比较日期先后
    //LocalDateTime.now().isBefore(),
    //LocalDateTime.now().isAfter(),

    //将字符串转换为localDateTime
    public static LocalDateTime convertStrToLDT(String date,String pattern) {
        return LocalDateTime.parse(date,DateTimeFormatter.ofPattern(pattern));
    }

    //Date转换为LocalDateTime
    public static LocalDateTime convertDateToLDT(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    //LocalDateTime转换为Date
    public static Date convertLDTToDate(LocalDateTime time) {
        return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
    }


    //获取指定日期的毫秒
    public static Long getMilliByTime(LocalDateTime time) {
        return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    //获取指定日期的秒
    public static Long getSecondsByTime(LocalDateTime time) {
        return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
    }

    //获取指定时间的指定格式
    public static String formatTime(LocalDateTime time, String pattern) {
        return time.format(DateTimeFormatter.ofPattern(pattern));
    }

    //获取指定时间格式的字符串
    public static String formatLDT(LocalDateTime time,String pattern) {
        return DateTimeFormatter.ofPattern(pattern).format(time);
    }

    //获取当前时间的指定格式
    public static String formatNow(String pattern) {
        return formatTime(LocalDateTime.now(), pattern);
    }

    //日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
    public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
        return time.plus(number, field);
    }

    // 解析 yyyy-MM-dd 字符串 为 LocalDate
    public static LocalDate parseLocalDateOrNow(String date) {
        LocalDate localDate;
        if(StringUtil.isEmpty(date)){
            localDate = LocalDate.now();
        }else{
            localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        return localDate;
    }

    //日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
    public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
        return time.minus(number, field);
    }

    /**
     * 转换为从现在开始的人性化表达: 日期/几天/小时/分钟前
     * @return
     */
    public static String getDescFromNow(LocalDateTime time){
        long minutes = betweenTwoTime(time,LocalDateTime.now(),ChronoUnit.MINUTES);
        if(minutes<-3) {
            return "未知";
        }else if(minutes<3) {
            return "刚刚";
        }else if(minutes<60){
            return minutes+"分钟前";
        }else if(minutes<60*24){
            long s = minutes/60;
            return s + "小时前";
        }else if(minutes<60*72){
            long s = minutes/(60*24);
            return s + "天前";
        }else{
            return time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
    }
    /**
     * 获取周几
     * @param time
     * @return
     */
    public static String getWeekDesc(LocalDateTime time){
        if(null==time){ return ""; }
        return "周" + "周一二三四五六日".charAt(DateUtil.getWeekOfDate(DateUtil.getDate(time)));
//        return WeekdayEnum.keyMap.get(
//                DateUtil.getWeekOfDate(DateUtil.getDate(time))+""
//        ).getWeek();
    }
    /**
     * 获取两个日期的差  field参数为ChronoUnit.*
     *
     * @param startTime
     * @param endTime
     * @param field     单位(年月日时分秒)
     * @return
     */
    public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
        Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
        if (field == ChronoUnit.YEARS) return period.getYears();
        if (field == ChronoUnit.MONTHS) return period.getYears() * 12 + period.getMonths();
        return field.between(startTime, endTime);
    }

    //获取一天的开始时间，2017,7,22 00:00
    public static LocalDateTime getDayStart(LocalDateTime time) {
        return time.withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);
    }

    //获取一天的结束时间，2017,7,22 23:59:59.999999999
    public static LocalDateTime getDayEnd(LocalDateTime time) {
        return time.withHour(23)
                .withMinute(59)
                .withSecond(59);
//                .withNano(999999999);
    }

    public static int getWeeks(LocalDate time) {
        //获取该年的第一天是星期几
        int week = time.withMonth(1).withDayOfMonth(1).getDayOfWeek().getValue();
        if (week == 1) {
            return time.getYear() % 100 * 100 + 1;
        }
        LocalDate countTime = time.minusDays(8 - week);
        int year = countTime.getYear();
        int dayOfYear = countTime.getDayOfYear();
        if (year != time.getYear()) {
            LocalDate lastYear = countTime.withMonth(12).withDayOfMonth(31);
            dayOfYear = lastYear.getDayOfYear();
            return year % 100 * 100 + (dayOfYear/7);
        }
        return year % 100 * 100 + (dayOfYear/7 + 1);
    }

    public static String getYearMonth(LocalDate now) {
        return String.format("%d%02d",now.getYear(),now.getMonthValue());
    }

    /**
     * 获取指定格式区间
     * @return string
     */
    public static String getRangStr(LocalDate start,LocalDate end) {
        return String.format("%d月%d日-%d月%d日",start.getMonthValue(),start.getDayOfMonth(),end.getMonthValue(),end.getDayOfMonth());
    }

    public static LocalDate getCurrentMonday() {
        LocalDate now = LocalDate.now();
        int value = now.getDayOfWeek().getValue();
        return now.minusDays(value -1);
    }

    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now().withYear(2018).withMonth(1).withDayOfMonth(1);
        System.out.println(getWeeks(localDate));
    }
}